package com.jwaoo.chat.fragment.session.repository;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import com.dx.as.common.ILoadListener;
import com.dx.as.listener.IProInterface;
import com.dx.as.listener.IViewInterface;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.fragment.session.SessionFragment;
import com.jwaoo.chat.fragment.session.bean.SessionBean;
import com.jwaoo.chat.fragment.session.model.SessionModel;
import com.jwaoo.chat.session.Extras;
import com.jwaoo.chat.session.SimpleClickListener;
import com.jwaoo.chat.session.recent.SessionCallback;
import com.jwaoo.chat.session.recent.adpter.SessionAdapter;
import com.jwaoo.chat.session.recent.drop.DropManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jwaoo on 2017/7/3.
 */

public class SessionRep extends IProInterface {
    // data
    private List<SessionBean> items;
    private SessionAdapter adapter;
    private SessionCallback callback;
    //记录session 条目，为单独刷新条目做准备
    private Map<Integer,Integer> map = new HashMap<>();
    private SessionModel sessionModel;
    private ISessionInterface iViewInterface;
    private MessageReiceiver messageReiceiver;
    private Activity activity;
    public SessionRep(Activity activity , ISessionInterface iViewInterface) {
        super(activity);
        this.activity = activity;
        sessionModel = new SessionModel(getContext(),loadListener);
        this.iViewInterface = iViewInterface;
    }

    @Override
    public void getDataFromNetOrDB(Object ... parms) {
    }

    @Override
    public void initialataData() {
        items = new ArrayList<>();
        initCallBack();
        adapter = new SessionAdapter(null,items);
        adapter.setCallback(callback);
        // drop listener
        DropManager.getInstance().setDropListener(new DropManager.IDropListener() {
            @Override
            public void onDropBegin() {
                touchListener.setShouldDetectGesture(false);
            }

            @Override
            public void onDropEnd() {
                touchListener.setShouldDetectGesture(true);
            }
        });
    }

    public void onResume(){
        getData();
        initRecieiver();
    }

    public void onPause(){
        getContext().unregisterReceiver(messageReiceiver);
    }

    private void initCallBack() {
        if (callback != null) {
            return;
        }
        callback = new SessionCallback() {
            @Override
            public void onRecentContactsLoaded() {

            }

            @Override
            public void onUnreadCountChange(int unreadCount) {

            }

            @Override
            public void onItemClick(SessionBean recent) {
                recent.setCount(0);
                recent.setStatus(ChatConstants.success);
                MessageHandler.getInstace(getContext()).handlerMessages(MessageHandler.UPDATE_SESSION,recent);
                iViewInterface.onItemClick(recent);
            }

            @Override
            public String getDigestOfAttachment( int msgType) {
                return null;
            }

            @Override
            public String getDigestOfTipMsg(SessionBean recent) {
                return null;
            }
        };
    }

    private void sortSessions(List<SessionBean> list) {
        if (list.size() == 0) {
            return;
        }
        Collections.sort(list, comp);
    }

    public SessionAdapter getAdapter(){
        return this.adapter;
    }

    private static Comparator<SessionBean> comp = new Comparator<SessionBean>() {

        @Override
        public int compare(SessionBean o1, SessionBean o2) {
            // 先比较置顶tag
            long time = o1.getTimestamp() - o2.getTimestamp();
            return time == 0 ? 0 : (time > 0 ? -1 : 1);
        }
    };

    private void initRecieiver(){
        messageReiceiver = new MessageReiceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ChatConstants.ACTION);
        getContext().registerReceiver(messageReiceiver, intentFilter);
    }

    private SimpleClickListener<SessionAdapter> touchListener = new SimpleClickListener<SessionAdapter>() {
        @Override
        public void onItemClick(SessionAdapter adapter, View view, int position) {
            if (callback != null) {
                SessionBean recent = adapter.getItem(position);
                callback.onItemClick(recent);
            }
        }

        @Override
        public void onItemLongClick(SessionAdapter adapter, View view, int position) {
//            showLongClickMenu(adapter.getItem(position), position);
        }

        @Override
        public void onItemChildClick(SessionAdapter adapter, View view, int position) {

        }

        @Override
        public void onItemChildLongClick(SessionAdapter adapter, View view, int position) {

        }
    };

    public SimpleClickListener<SessionAdapter> getOnTouchListener(){
        return this.touchListener;
    }

    public void getData(){
        sessionModel.getData();
    }

    private ILoadListener<List<SessionBean>> loadListener = new ILoadListener<List<SessionBean>>() {
        @Override
        public void onResponse(final List<SessionBean> response, int flg) {
            items.clear();
            for (int i = 0; i < response.size(); i ++){
                SessionBean sessionBean = response.get(i);
                map.put(sessionBean.getFriend(),i);
            }
            sortSessions(items);
            items.addAll(response);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                    iViewInterface.onResponse(response);
                }
            });

        }

        @Override
        public void onFailure(Throwable t) {

        }
    };

    private class MessageReiceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getData();
        }
    }
}
